
import { $route } from "../navigate/index"
import { _toast } from "../utils"
import $api from "../common/index"

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

const isJSON = (str) => {
  if (typeof str === 'string') {
    try {
      let obj=JSON.parse(str);
      if(typeof obj === 'object' && obj ){
        return true;
      }else{
        return false;
      }
    } catch(e) {
      return false;
    }
  }
  return false;
}

/**
 * 添加默认参数
 * */ 
const _addDefaultParams = (config) => {
  let systemInfo = wx.getSystemInfoSync() || {};
  let token = wx.getStorageSync('token');
  let skid = wx.getStorageSync('skid');
  let data = config;
  config.system = systemInfo.system ? systemInfo.system.split(' ')[0] : '';
  config.token = data.token ? data.token : token ? token : '';
  config.skid = data.skid ? data.skid : skid ? skid : $api.getEnvSkid();
  return config;
}

/**
 * 处理对象中的undefined
 * */ 
const _deleteUndefined = (opts) => {
  for(let key in opts){
    if(typeof(opts[key]) == 'undefined' || opts[key] == 'undefined'){
      opts[key] = '';
    } else if (Object.prototype.toString.call(opts[key])==='[object Object]'){
      opts[key] = _deleteUndefined(opts[key]);
    }
  }
  return opts;
}

/**
 * 对图片后缀统一处理
 */
const _imgSuffixHandler = (opts) => {
  let data = JSON.stringify(opts);
  data = data.replace(/.png.png/g,'.png');
  data = data.replace(/.jpg.png/g,'.jpg');
  data = JSON.parse(data);
  return data;
}

/**
 * 返回结果输出
 * */ 
const _consoleResult = (opts) => {
  let config = opts.config;
  let server_data = opts.data;
  console.log(`请求时间：${(+new Date() - config.startTime) / 1000}s`)
  console.log(`请求地址：${config.url}`)
  console.log(`请求参数：${JSON.stringify(config.data)}`)
  console.log(`******************************返回结果********************************`)
  console.log('请求返回：', server_data)
  console.log( '\n\n' )
}

/**
 * 返回结果判断处理,成功数据处理方法
 * */ 
const _successDataHandle = (data, axios) => {
  let page = null;
  if(data.code === 403 || data.code === 40301){
    let pages = getCurrentPages();
    page = pages[pages.length - 1];
  }
  data = _imgSuffixHandler(data);
  switch( data.code ){
    case 200:
      return data.data;
    case 400 || 600:
      let msg = data.message;
      msg = msg.indexOf("地址有误") > -1 ? '地址有误,请重新选择所在地区！' : msg;
      _toast(msg);
      return Promise.reject({code: data.code, message: msg});
    case 40302:
      // 统计规定5min时间内,限制再次刷新token次数5次
      // collectTask.wxappRefreshTokenCount += 1;
      // if(collectTask.hasExceedLimit()){
      //   axios.wxappRefreshToken(40302);
      // }
      axios.wxappRefreshToken();
      return Promise.reject({code: data.code, message: data.message});
    case 403:
      if(page && page.route.indexOf('getUserInfo') !== -1){
        break;
      } 
      $route({ url: '../../pages/getUserInfo/index'});
      return Promise.reject({code: data.code, message: data.message});
    case 40301:
      if(page && page.route.indexOf('signIn') !== -1){
        break;
      }
      $route({ url: '../../pages/signIn/signIn'});
      return Promise.reject({code: data.code, message: data.message});
    default:
      _toast(data.message);
      return Promise.reject({code: data.code, message: data.message});
  }
}

module.exports = {
  formatTime,
  isJSON,
  _addDefaultParams,
  _deleteUndefined,
  _imgSuffixHandler,
  _consoleResult,
  _successDataHandle
}
